package com.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.bean.LineTable;
import com.bean.UserList;
import com.bean.ZanMessage;
import com.dao.LineTableDao;
import com.util.CodeUtil;
import com.util.Domain;
import com.util.Pager;
@Component
public class LineTableDaoImpl implements LineTableDao{

	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Override
	public Pager<LineTable> selectUsersLine(Integer curPage,Integer pageSize,String uid,String wuid){
		Pager<LineTable> pager=new Pager<LineTable>();
		if(curPage!=null)
			pager.setCurPage(curPage);
		if(pageSize!=null)
			pager.setPageSize(pageSize);
		UserList ulist=mongoTemplate.findById(wuid, UserList.class);
		Query query=new Query();
		List<ObjectId> ids=new ArrayList<ObjectId>();
		if(ulist!=null&&ulist.getPlains()!=null&&ulist.getPlains().length>0){
			for(String plains:ulist.getPlains()){
				ids.add(new ObjectId(plains));
			}
			query.addCriteria(Criteria.where("_id").in(ids));
		}
		query.addCriteria(Criteria.where("isDelete").is("n"));
		List<LineTable> lines=mongoTemplate.find(
				query.skip(pager.getStart()).
					limit(pager.getPageSize()), 
					LineTable.class);
		List<LineTable> data=new ArrayList<>();
		List<Integer> indexes=CodeUtil.randomIndexes1(lines.size());
		for(Integer index:indexes){
			LineTable lineTable=lines.get(index);
			Query zanQuery=new Query(Criteria.where("users.uid").is(uid).and("objId").is(new ObjectId(lineTable.getId())).and("isDelete").is(Domain.zan_message_is_delete_n)
					.and("textTypes").is(Domain.zan_message_text_types_line));
			long count=mongoTemplate.count(zanQuery, ZanMessage.class);
			if(count>0){
				lineTable.setLikes(1);
			}else{
				lineTable.setLikes(0);
			}
			data.add(lineTable);
		}
		pager.setData(data);
		long count=mongoTemplate.count(query, LineTable.class);
		pager.setTotalRow(Integer.valueOf(String.valueOf(count)));
		return pager;
	}
}
